package com.zhongxi.guoyuan.OffLineShop.UI;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhongxi.guoyuan.OffLineShop.Adapter.ShopListAdapter;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.Model.ItemShopInfo;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.widget.view.LoadMoreRecyclerView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/4/3.
 */

public class OffLineSearchActivity extends OffLineBaseActivity {
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.tv_cancle_search)
    TextView mTvCancleSearch;
    @Bind(R.id.iv_shoper_search)
    ImageView mIvShoperSearch;
    @Bind(R.id.et_search_offLine)
    EditText mEtSearchOffLine;
    @Bind(R.id.tv_shoper_clear)
    TextView mTvShoperClear;
    @Bind(R.id.recycleView)
    LoadMoreRecyclerView mRecycleView;
    @Bind(R.id.swipRefreshlayout)
    SwipeRefreshLayout mSwipRefreshlayout;
    private List<ItemShopInfo> mShopInfoList = new ArrayList<>();
    private ShopListAdapter mAdapter;
    Handler mHandler = new Handler();

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_offlinesearch);
        ButterKnife.bind(this);
    }

    @Override
    protected void initActionBar() {
        super.initActionBar();
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationIcon(R.mipmap.topback);
        mTvName.setText("线下商家搜索");
    }

    @Override
    protected void initView() {
        super.initView();
        mEtSearchOffLine.setFocusable(false);  // 刚进来时使输入框失去焦点
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ShopListAdapter(mShopInfoList, 0);
        mRecycleView.setAdapter(mAdapter);
        mSwipRefreshlayout.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.RED, Color.YELLOW);
        mSwipRefreshlayout.setEnabled(false);
    }

    @Override
    protected void initNetWork() {
        super.initNetWork();
        getShopList();
    }

    @Override
    protected void initListener() {
        super.initListener();
        mEtSearchOffLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtSearchOffLine.setFocusable(true);//设置输入框可聚集
                mEtSearchOffLine.setFocusableInTouchMode(true);//设置触摸聚焦
                mEtSearchOffLine.requestFocus();//请求焦点
                mEtSearchOffLine.findFocus();//获取焦点
                CommonTool.showSoft(mEtSearchOffLine, OffLineSearchActivity.this);
            }
        });
        mEtSearchOffLine.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                mTvCancleSearch.setVisibility(View.VISIBLE);
                mTvCancleSearch.setText(getString(R.string.cancel));
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    mTvShoperClear.setVisibility(View.VISIBLE);
                    mTvCancleSearch.setText(getString(R.string.search));
                } else {
                    mTvCancleSearch.setText(getString(R.string.cancel));
                    mTvShoperClear.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        // 加载更多条目
        mRecycleView.setOnLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener() {
            @Override
            public void loadingMore() {
                mAdapter.setLoadingState(mAdapter.LOADING);
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                page++;
                                String mTrim = mEtSearchOffLine.getText().toString().trim();
                                if (TextUtils.isEmpty(mTrim)) {
                                    getShopList();
                                } else {
                                    postShopList(mTrim);
                                }
                            }
                        });
                    }
                }, 1000);
            }
        });

        mAdapter.setOnItemClickListener(new ShopListAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                Intent mIntent = new Intent(UiUtils.getContext(), OffLineShopDetailActivtiy.class);
                mIntent.putExtra("offlineshopid", mShopInfoList.get(position).getId());
                startActivity(mIntent);
            }
        });

    }



    @OnClick({R.id.tv_cancle_search, R.id.iv_shoper_search, R.id.tv_shoper_clear})
    public void onViewClicked(View view) {
        String mTrim = mEtSearchOffLine.getText().toString().trim();
        switch (view.getId()) {
            case R.id.iv_shoper_search:
                CommonTool.hideSoft(mEtSearchOffLine, this);
                page = 1;
                if (TextUtils.isEmpty(mTrim)) {
                    ToastUtil.show(getString(R.string.input_empty));
                } else {
                    postShopList(mTrim);
                }
                break;
            case R.id.tv_shoper_clear:
                mEtSearchOffLine.setText("");
                CommonTool.showSoft(mEtSearchOffLine, this);
                break;
            case R.id.tv_cancle_search:
                CommonTool.hideSoft(mEtSearchOffLine, this);
                page = 1;
                if (TextUtils.isEmpty(mTrim)) {     //  取消  从新获取全部数据
                    mTvCancleSearch.setVisibility(View.GONE);
                    getShopList();
                } else {
                    postShopList(mTrim);
                }
                break;
        }
    }

    private void getShopList() {
        mSwipRefreshlayout.setRefreshing(true);
        unsubscribe();
        mDisposable = NetWork.getOffLineApi()
                .getMarketshopOfEntry(RelativeUrl.StoreList + MyApplication.getInstance().getUrl(), MyApplication.getInstance().getCheck(false),
                        page, 1, "0", MyApplication.getInstance().getLongitude(), MyApplication.getInstance().getLatitude())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        mSwipRefreshlayout.setRefreshing(false);
                        if (page == 1) {
                            mShopInfoList.clear();
                        }
                        JSONObject jsonObject = new JSONObject(responseBody.string());
                        JSONObject safeobj = jsonObject.optJSONObject("safeobj");
                        MyApplication.getInstance().sharedPrefrences.edit().putString("now", safeobj.optString("now")).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", safeobj.optString("safestring")).commit();
                        int mCode = jsonObject.optInt("code");
                        if (mCode == 1) {
                            JSONArray mJSONArray = jsonObject.optJSONArray("data");
                            JSONObject mObject = jsonObject.optJSONObject("cateInfo");
                            if (mJSONArray != null && mJSONArray.length() > 0) {
                                for (int i = 0; i < mJSONArray.length(); i++) {
                                    ItemShopInfo mItemShopInfo = ItemShopInfo.getParseObject((JSONObject) mJSONArray.get(i));
                                    String mCateName = mObject.optString(((JSONObject) mJSONArray.get(i)).optString("cateid"));
                                    mItemShopInfo.setCateName(mCateName);
                                    mShopInfoList.add(mItemShopInfo);
                                }
                                mAdapter.notifyDataSetChanged();
                                mAdapter.setLoadingState(mAdapter.LOADCOMPLENT);
                            } else {
                                if (page > 1) {
                                    mAdapter.setLoadingState(mAdapter.LOADEND);
                                    page--;
                                }
                            }
                        } else if (mCode == 2816) {
                            logoutDialog();
                        } else {
                            if (page > 1) {
                                page--;
                            }
                            ToastUtil.show(getString(R.string.loseData, mCode));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mSwipRefreshlayout.setRefreshing(false);
                        if (page > 1) {
                            page--;
                        }
                        ToastUtil.show(getString(R.string.load_error_shopList));
                    }
                });
    }

    /**
     * post 的请求
     *
     * @param trim
     */
    private void postShopList(final String trim) {
        mSwipRefreshlayout.setRefreshing(true);
        unsubscribe();
        mDisposable = NetWork.getOffLineApi().searchStores(RelativeUrl.SearchStores + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), page,
                MyApplication.getInstance().getLongitude(), MyApplication.getInstance().getLatitude(), trim)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        mSwipRefreshlayout.setRefreshing(false);
                        if (page == 1) {
                            mShopInfoList.clear();
                        }
                        JSONObject jsonObject = new JSONObject(responseBody.string());
                        JSONObject safeobj = jsonObject.optJSONObject("safeobj");
                        MyApplication.getInstance().sharedPrefrences.edit().putString("now", safeobj.optString("now")).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", safeobj.optString("safestring")).commit();
                        int mCode = jsonObject.optInt("code");
                        if (mCode == 1) {
                            JSONArray mJSONArray = jsonObject.optJSONArray("data");
                            JSONObject mObject = jsonObject.optJSONObject("cateInfo");
                            if (mJSONArray != null && mJSONArray.length() > 0) {
                                for (int i = 0; i < mJSONArray.length(); i++) {
                                    ItemShopInfo mItemShopInfo = ItemShopInfo.getParseObject((JSONObject) mJSONArray.get(i));
                                    String mCateName = mObject.optString(((JSONObject) mJSONArray.get(i)).optString("cateid"));
                                    mItemShopInfo.setCateName(mCateName);
                                    mShopInfoList.add(mItemShopInfo);
                                }
                                mAdapter.notifyDataSetChanged();
                                mAdapter.setLoadingState(mAdapter.LOADCOMPLENT);
                            } else {
                                if (page > 1) {
                                    mAdapter.setLoadingState(mAdapter.LOADEND);
                                    page--;
                                } else {
                                    mShopInfoList.clear();
                                    mAdapter.notifyDataSetChanged();
                                    ToastUtil.show(getString(R.string.no_search, trim));
                                }
                            }
                        } else if (mCode == 2816) {
                            logoutDialog();
                        } else {
                            if (page > 1) {
                                page--;
                            }
                            ToastUtil.show(getString(R.string.loseData, mCode));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mSwipRefreshlayout.setRefreshing(false);
                        if (page > 1) {
                            page--;
                        }
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(this).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                clearData();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        clearData();
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearData() {
        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", "").commit();
            SpUtils.getInstance().saveSp("shopid", "");
            SpUtils.getInstance().saveSp("mdffline", "");
            SpUtils.getInstance().saveSp("orderid", "");
            finish();
            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
        }
    }

}
